package middleware

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/slrun/callcenter/internal/service"
)

// AuthMiddleware 认证中间件
func AuthMiddleware(systemService *service.SystemService) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头获取Authorization
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "缺少认证令牌"})
			c.Abort()
			return
		}

		// 解析Bearer令牌
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "认证令牌格式错误"})
			c.Abort()
			return
		}

		tokenString := parts[1]

		// 验证令牌
		token, claims, err := systemService.ValidateJWT(tokenString)
		if err != nil || !token.Valid {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的认证令牌"})
			c.Abort()
			return
		}

		// 提取用户信息并存储到上下文
		userID := (*claims)["user_id"].(string)
		username := (*claims)["username"].(string)
		roleID := (*claims)["role_id"].(string)

		c.Set("user_id", userID)
		c.Set("username", username)
		c.Set("role_id", roleID)
		c.Set("token", tokenString)

		c.Next()
	}
}

// PermissionMiddleware 权限检查中间件
func PermissionMiddleware(systemService *service.SystemService, requiredPermission string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从上下文获取用户ID
		userID, exists := c.Get("user_id")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未认证的请求"})
			c.Abort()
			return
		}

		// 检查用户是否有指定权限
		hasPermission, err := systemService.CheckUserPermission(userID.(string), requiredPermission)
		if err != nil || !hasPermission {
			c.JSON(http.StatusForbidden, gin.H{"error": "没有权限执行此操作", "required_permission": requiredPermission})
			c.Abort()
			return
		}

		c.Next()
	}
}

// RoleMiddleware 角色检查中间件
func RoleMiddleware(allowedRoles ...string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从上下文获取角色ID
		roleID, exists := c.Get("role_id")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未认证的请求"})
			c.Abort()
			return
		}

		// 检查角色是否在允许列表中
		allowed := false
		for _, role := range allowedRoles {
			if roleID.(string) == role {
				allowed = true
				break
			}
		}

		if !allowed {
			c.JSON(http.StatusForbidden, gin.H{"error": "当前角色没有权限访问此资源", "allowed_roles": allowedRoles})
			c.Abort()
			return
		}

		c.Next()
	}
}

// CORS 跨域中间件
func CORS() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Credentials", "true")
		c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Header("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}

// RequestLogger 请求日志中间件
func RequestLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 开始时间
		start := gin.DefaultWriter

		// 处理请求
		c.Next()

		// 请求信息
		method := c.Request.Method
		path := c.Request.URL.Path
		status := c.Writer.Status()
		clientIP := c.ClientIP()

		// 记录日志（实际应用中应使用标准日志库）
		fmt.Fprintf(start, "%s | %3d | %13v | %15s | %s | %s\n",
			c.Request.Context().Value("request_id"),
			status,
			c.Writer.Size(),
			clientIP,
			method,
			path,
		)
	}
}